package com.wzh.easyapi.config;

import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.wzh.easyapi.bean.DataSourceEntity;
import com.wzh.easyapi.form.SQLRequest;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class DruidDataSourceManager {

    private static final Map<String, DataSource> DATA_SOURCE_CACHE = new ConcurrentHashMap<>();

    public DataSource getDataSource(DataSourceEntity dataSourceEntity) {
        return getDataSource(dataSourceEntity,true);
    }
    /**
     * 获取数据源，如果不存在则动态创建并缓存
     * @return DataSource
     * @throws Exception 如果加载失败
     */
    @SneakyThrows
    public DataSource getDataSource(DataSourceEntity dataSourceEntity,Boolean cache) {
        // 检查缓存
        if (cache && ObjectUtil.isNotEmpty(dataSourceEntity.getId())
                && DATA_SOURCE_CACHE.containsKey(dataSourceEntity.getId())) {
            return DATA_SOURCE_CACHE.get(dataSourceEntity.getId());
        }
        Resource resource = new ClassPathResource("lib/"+dataSourceEntity.getJarName());
        // 动态加载 JAR 包
        ClassLoader classLoader = ClassLoaderUtil.getJarClassLoader(resource.getFile());

        // 设置当前线程的 ClassLoader
        Thread.currentThread().setContextClassLoader(classLoader);

        // 创建 DruidDataSource
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dataSourceEntity.getDriverClassName());
        dataSource.setUrl(dataSourceEntity.getJdbcUrl());
        dataSource.setUsername(dataSourceEntity.getUsername());
        dataSource.setPassword(dataSourceEntity.getPassword());

        // 可选的连接池参数
        dataSource.setInitialSize(5);
        dataSource.setMinIdle(5);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(60000);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestWhileIdle(true);
        // 禁用自动重试
        dataSource.setBreakAfterAcquireFailure(true);
        dataSource.setConnectionErrorRetryAttempts(3);

        // 缓存数据源
        if (cache && ObjUtil.isNotEmpty(dataSourceEntity.getId())) {
            DATA_SOURCE_CACHE.put(dataSourceEntity.getId(), dataSource);
        }
        return dataSource;
    }

    /**
     * 移除数据源
     */
    public void removeDataSource(String dataSourceId) {
        DataSource dataSource = DATA_SOURCE_CACHE.remove(dataSourceId);
        if (dataSource instanceof DruidDataSource) {
            ((DruidDataSource) dataSource).close();
        }
    }

    /**
     * 清理所有数据源
     */
    public void clearAllDataSources() {
        DATA_SOURCE_CACHE.values().forEach(dataSource -> {
            if (dataSource instanceof DruidDataSource) {
                ((DruidDataSource) dataSource).close();
            }
        });
        DATA_SOURCE_CACHE.clear();
    }
}
